package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.user.request.UserUpdateRequest;
import com.blog.cmrpersonalblog.dto.user.response.UserResponse;
import com.blog.cmrpersonalblog.service.UnifiedFileUploadService;
import com.blog.cmrpersonalblog.enums.FileUploadType;
import com.blog.cmrpersonalblog.service.SysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 用户头像管理控制器
 * 允许用户管理自己的头像
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckLogin
public class UserAvatarController {

   @Resource
    private UnifiedFileUploadService unifiedFileUploadService;

   @Resource
    private SysUserService sysUserService;

    /**
     * 删除当前用户头像
     */
    @DeleteMapping("/deleteAvatar")
    public Result<Void> deleteMyAvatar() {
        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("用户删除头像: userId={}", currentUserId);
        
        try {
            // 获取当前用户信息
            UserResponse currentUser = sysUserService.getUserDetail(currentUserId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            // 删除头像文件
            if (currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
                String relativePath = extractRelativePathFromUrl(currentUser.getAvatar());
                if (relativePath != null) {
                    unifiedFileUploadService.deleteFile(relativePath, FileUploadType.AVATAR);
                }
            }

            // 清空用户头像URL
            UserUpdateRequest updateRequest = new UserUpdateRequest();
            updateRequest.setUserId(currentUserId);
            updateRequest.setAvatar("");
            updateRequest.setUpdateBy(StpUtil.getLoginIdAsString());
            
            boolean success = sysUserService.updateUser(updateRequest);
            if (success) {
                return Result.success("头像删除成功");
            } else {
                return Result.error("头像删除失败");
            }
        } catch (Exception e) {
            log.error("删除头像失败", e);
            return Result.error("删除头像失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户头像信息
     */
    @GetMapping("/getAvatar")
    public Result<String> getMyAvatar() {
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();
            UserResponse currentUser = sysUserService.getUserDetail(currentUserId);
            
            if (currentUser == null) {
                return Result.error("用户不存在");
            }
            
            String avatarUrl = currentUser.getAvatar();
            return Result.success(avatarUrl != null ? avatarUrl : "");
        } catch (Exception e) {
            log.error("获取头像信息失败", e);
            return Result.error("获取头像信息失败：" + e.getMessage());
        }
    }

    /**
     * 从文件URL中提取相对路径
     */
    private String extractRelativePathFromUrl(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return null;
        }
        
        // 假设URL格式为: /files/UserAvatar/avatar_1_20240101120000_abcd1234.jpg
        // 提取相对路径: /UserAvatar/avatar_1_20240101120000_abcd1234.jpg
        int filesIndex = fileUrl.indexOf("/files");
        if (filesIndex != -1) {
            return fileUrl.substring(filesIndex + 6); // 去掉 "/files" 部分
        }
        
        return null;
    }
}
